/*
 * Copyright © 2012 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners.
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.gfxsensorsdemo.sensors;

import com.nokia.example.gfxsensorsdemo.ArrayUtils;

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.sensor.ChannelInfo;
import javax.microedition.sensor.Data;
import javax.microedition.sensor.DataListener;
import javax.microedition.sensor.SensorConnection;
import javax.microedition.sensor.SensorInfo;
import javax.microedition.sensor.SensorManager;

/**
 * Implementation for AccelerationProvider
 */
class AccelerationProviderImpl
        extends AccelerationProvider
        implements DataListener {

    private SensorConnection sensor;
    private int dataType;

    public AccelerationProviderImpl()
            throws IOException {
        initConnection();
    }

    /**
     * Close the sensor connection
     */
    public void close() {
        sensor.removeDataListener();
        try {
            sensor.close();
            sensor = null;
        }
        catch (IOException ioe) {
        }
    }

    /**
     * Handle sensor received data
     */
    public void dataReceived(SensorConnection sc, Data[] data, boolean isDataLost) {
        switch (dataType) {
            case ChannelInfo.TYPE_DOUBLE:
                dataReceived(ArrayUtils.getLast(data[0].getDoubleValues()),
                             ArrayUtils.getLast(data[1].getDoubleValues()),
                             ArrayUtils.getLast(data[2].getDoubleValues()));
                break;
            default:
                break;
        }
    }

    /**
     * Initialize connection to acceleration sensors
     */
    private void initConnection() throws IOException {
        SensorInfo infos[] = SensorManager.findSensors("acceleration", null);
        if (infos.length > 0) {
            dataType = infos[0].getChannelInfos()[0].getDataType();
            try {
                sensor = (SensorConnection) Connector.open(infos[0].getUrl());
                sensor.setDataListener(this, 1);
            }
            catch (SecurityException se) {
                throw new IOException("could not open sensor");
            }
            catch (IOException ioe) {
                throw new IOException("could not open sensor");
            }
            catch (IllegalArgumentException iae) {
                throw new IOException("could not open sensor");
            }
        }
        else {
            throw new IOException("acceleration sensor not found");
        }
    }
}
